<template>
  <div class="space-y-6">
    <!-- 页面标题和操作 -->
    <div class="flex items-center justify-between">
      <div>
        <h1 class="text-2xl font-bold text-gray-900">驾驶员管理</h1>
        <p class="text-gray-600 mt-1">管理驾驶员信息和资质</p>
      </div>
      <el-button type="primary" :icon="Plus" @click="showAddDialog = true">
        添加驾驶员
      </el-button>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-card>
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <el-input
          v-model="searchQuery"
          placeholder="搜索姓名、电话或驾照号"
          :prefix-icon="Search"
          clearable
        />
        <el-select v-model="statusFilter" placeholder="驾驶员状态" clearable>
          <el-option label="在职" value="active" />
          <el-option label="休假" value="on_leave" />
          <el-option label="离职" value="inactive" />
        </el-select>
        <el-select v-model="licenseFilter" placeholder="驾照类型" clearable>
          <el-option label="C1" value="C1" />
          <el-option label="C2" value="C2" />
          <el-option label="B1" value="B1" />
          <el-option label="B2" value="B2" />
          <el-option label="A1" value="A1" />
          <el-option label="A2" value="A2" />
        </el-select>
        <el-button @click="resetFilters">重置筛选</el-button>
      </div>
    </el-card>
    
    <!-- 驾驶员列表 -->
    <el-card>
      <el-table :data="filteredDrivers" stripe style="width: 100%">
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :src="row.avatar" :icon="UserFilled" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="phone" label="电话" width="130" />
        <el-table-column prop="licenseNumber" label="驾照号" width="150" />
        <el-table-column prop="licenseType" label="驾照类型" width="100" />
        <el-table-column prop="experience" label="驾龄(年)" width="100" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              size="small"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentVehicle" label="当前车辆" width="120" />
        <el-table-column prop="totalTrips" label="总行程" width="100" />
        <el-table-column prop="rating" label="评分" width="100">
          <template #default="{ row }">
            <el-rate
              v-model="row.rating"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewDriver(row)">查看</el-button>
            <el-button size="small" type="primary" @click="editDriver(row)">编辑</el-button>
            <el-dropdown @command="handleCommand">
              <el-button size="small" type="info">
                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: 'trips', driver: row }">
                    行程记录
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'violations', driver: row }">
                    违章记录
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'performance', driver: row }">
                    绩效评估
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'delete', driver: row }" divided>
                    删除驾驶员
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="flex justify-center mt-6">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="drivers.length"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑驾驶员对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingDriver ? '编辑驾驶员' : '添加驾驶员'"
      width="700px"
    >
      <el-form
        ref="driverFormRef"
        :model="driverForm"
        :rules="driverRules"
        label-width="100px"
      >
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="driverForm.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select v-model="driverForm.gender" placeholder="选择性别" class="w-full">
              <el-option label="男" value="male" />
              <el-option label="女" value="female" />
            </el-select>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input-number v-model="driverForm.age" :min="18" :max="65" class="w-full" />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="driverForm.phone" placeholder="请输入电话号码" />
          </el-form-item>
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="driverForm.idCard" placeholder="请输入身份证号" />
          </el-form-item>
          <el-form-item label="驾照号" prop="licenseNumber">
            <el-input v-model="driverForm.licenseNumber" placeholder="请输入驾照号" />
          </el-form-item>
          <el-form-item label="驾照类型" prop="licenseType">
            <el-select v-model="driverForm.licenseType" placeholder="选择驾照类型" class="w-full">
              <el-option label="C1" value="C1" />
              <el-option label="C2" value="C2" />
              <el-option label="B1" value="B1" />
              <el-option label="B2" value="B2" />
              <el-option label="A1" value="A1" />
              <el-option label="A2" value="A2" />
            </el-select>
          </el-form-item>
          <el-form-item label="驾龄(年)" prop="experience">
            <el-input-number v-model="driverForm.experience" :min="0" :max="50" class="w-full" />
          </el-form-item>
          <el-form-item label="入职日期" prop="hireDate">
            <el-date-picker
              v-model="driverForm.hireDate"
              type="date"
              placeholder="选择入职日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              class="w-full"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="driverForm.status" placeholder="选择状态" class="w-full">
              <el-option label="在职" value="active" />
              <el-option label="休假" value="on_leave" />
              <el-option label="离职" value="inactive" />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="地址" prop="address">
          <el-input v-model="driverForm.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="紧急联系人">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <el-input v-model="driverForm.emergencyContact" placeholder="紧急联系人姓名" />
            <el-input v-model="driverForm.emergencyPhone" placeholder="紧急联系人电话" />
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="driverForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" @click="saveDriver">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 驾驶员详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="驾驶员详情" width="800px">
      <div v-if="selectedDriver" class="space-y-6">
        <div class="flex items-start space-x-6">
          <el-avatar :size="80" :src="selectedDriver.avatar" :icon="UserFilled" />
          <div class="flex-1">
            <h2 class="text-xl font-bold text-gray-900">{{ selectedDriver.name }}</h2>
            <div class="mt-2 space-y-1">
              <p class="text-gray-600">驾照类型: {{ selectedDriver.licenseType }}</p>
              <p class="text-gray-600">驾龄: {{ selectedDriver.experience }} 年</p>
              <div class="flex items-center space-x-2">
                <span class="text-gray-600">状态:</span>
                <el-tag :type="getStatusType(selectedDriver.status)" size="small">
                  {{ getStatusText(selectedDriver.status) }}
                </el-tag>
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-gray-600">评分:</span>
                <el-rate
                  v-model="selectedDriver.rating"
                  disabled
                  show-score
                  text-color="#ff9900"
                  score-template="{value}"
                />
              </div>
            </div>
          </div>
        </div>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div class="space-y-4">
            <h3 class="text-lg font-medium text-gray-900">基本信息</h3>
            <div class="bg-gray-50 p-4 rounded-lg space-y-2">
              <div class="flex justify-between">
                <span class="text-gray-600">性别:</span>
                <span class="font-medium">{{ selectedDriver.gender === 'male' ? '男' : '女' }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">年龄:</span>
                <span class="font-medium">{{ selectedDriver.age }} 岁</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">电话:</span>
                <span class="font-medium">{{ selectedDriver.phone }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">身份证号:</span>
                <span class="font-medium">{{ selectedDriver.idCard }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">驾照号:</span>
                <span class="font-medium">{{ selectedDriver.licenseNumber }}</span>
              </div>
            </div>
          </div>
          <div class="space-y-4">
            <h3 class="text-lg font-medium text-gray-900">工作信息</h3>
            <div class="bg-gray-50 p-4 rounded-lg space-y-2">
              <div class="flex justify-between">
                <span class="text-gray-600">入职日期:</span>
                <span class="font-medium">{{ selectedDriver.hireDate }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">当前车辆:</span>
                <span class="font-medium">{{ selectedDriver.currentVehicle || '无' }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">总行程:</span>
                <span class="font-medium">{{ selectedDriver.totalTrips }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">总里程:</span>
                <span class="font-medium">{{ selectedDriver.totalMileage }} km</span>
              </div>
            </div>
          </div>
        </div>
        
        <div>
          <h3 class="text-lg font-medium text-gray-900 mb-2">联系信息</h3>
          <div class="bg-gray-50 p-4 rounded-lg space-y-2">
            <div class="flex justify-between">
              <span class="text-gray-600">地址:</span>
              <span class="font-medium">{{ selectedDriver.address }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-600">紧急联系人:</span>
              <span class="font-medium">{{ selectedDriver.emergencyContact }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-600">紧急联系电话:</span>
              <span class="font-medium">{{ selectedDriver.emergencyPhone }}</span>
            </div>
          </div>
        </div>
        
        <div v-if="selectedDriver.notes">
          <h3 class="text-lg font-medium text-gray-900 mb-2">备注</h3>
          <div class="bg-gray-50 p-4 rounded-lg">
            <p class="text-gray-700">{{ selectedDriver.notes }}</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, ArrowDown, UserFilled } from '@element-plus/icons-vue'

// 接口定义
interface Driver {
  id: number
  name: string
  gender: 'male' | 'female'
  age: number
  phone: string
  idCard: string
  licenseNumber: string
  licenseType: string
  experience: number
  status: 'active' | 'on_leave' | 'inactive'
  hireDate: string
  address: string
  emergencyContact: string
  emergencyPhone: string
  currentVehicle?: string
  totalTrips: number
  totalMileage: number
  rating: number
  avatar?: string
  notes?: string
}

// 响应式数据
const showAddDialog = ref(false)
const showDetailDialog = ref(false)
const editingDriver = ref<Driver | null>(null)
const selectedDriver = ref<Driver | null>(null)
const searchQuery = ref('')
const statusFilter = ref('')
const licenseFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 驾驶员表单
const driverForm = reactive({
  name: '',
  gender: 'male' as Driver['gender'],
  age: 25,
  phone: '',
  idCard: '',
  licenseNumber: '',
  licenseType: '',
  experience: 0,
  status: 'active' as Driver['status'],
  hireDate: '',
  address: '',
  emergencyContact: '',
  emergencyPhone: '',
  notes: ''
})

// 表单验证规则
const driverRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入电话号码', trigger: 'blur' }],
  idCard: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
  licenseNumber: [{ required: true, message: '请输入驾照号', trigger: 'blur' }],
  licenseType: [{ required: true, message: '请选择驾照类型', trigger: 'change' }],
  experience: [{ required: true, message: '请输入驾龄', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  hireDate: [{ required: true, message: '请选择入职日期', trigger: 'change' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
}

// 模拟驾驶员数据
const drivers = ref<Driver[]>([
  {
    id: 1,
    name: '王师傅',
    gender: 'male',
    age: 35,
    phone: '13800138001',
    idCard: '110101198901010001',
    licenseNumber: 'C1234567890123',
    licenseType: 'C1',
    experience: 10,
    status: 'active',
    hireDate: '2020-01-15',
    address: '北京市朝阳区xxx街道xxx号',
    emergencyContact: '王夫人',
    emergencyPhone: '13800138002',
    currentVehicle: '京A12345',
    totalTrips: 156,
    totalMileage: 25000,
    rating: 4.8,
    notes: '驾驶技术娴熟，服务态度好'
  },
  {
    id: 2,
    name: '李师傅',
    gender: 'male',
    age: 42,
    phone: '13800138003',
    idCard: '110101198201010002',
    licenseNumber: 'B1234567890124',
    licenseType: 'B2',
    experience: 15,
    status: 'active',
    hireDate: '2018-06-20',
    address: '北京市海淀区xxx街道xxx号',
    emergencyContact: '李夫人',
    emergencyPhone: '13800138004',
    currentVehicle: '',
    totalTrips: 203,
    totalMileage: 38000,
    rating: 4.6,
    notes: '经验丰富，可驾驶大型车辆'
  },
  {
    id: 3,
    name: '张师傅',
    gender: 'male',
    age: 28,
    phone: '13800138005',
    idCard: '110101199501010003',
    licenseNumber: 'C1234567890125',
    licenseType: 'C1',
    experience: 5,
    status: 'on_leave',
    hireDate: '2022-03-10',
    address: '北京市西城区xxx街道xxx号',
    emergencyContact: '张母',
    emergencyPhone: '13800138006',
    currentVehicle: '',
    totalTrips: 89,
    totalMileage: 12000,
    rating: 4.2,
    notes: '年轻有活力，学习能力强'
  }
])

// 计算属性
const filteredDrivers = computed(() => {
  let filtered = drivers.value
  
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(driver => 
      driver.name.toLowerCase().includes(query) ||
      driver.phone.includes(query) ||
      driver.licenseNumber.toLowerCase().includes(query)
    )
  }
  
  if (statusFilter.value) {
    filtered = filtered.filter(driver => driver.status === statusFilter.value)
  }
  
  if (licenseFilter.value) {
    filtered = filtered.filter(driver => driver.licenseType === licenseFilter.value)
  }
  
  return filtered
})

// 方法
const getStatusType = (status: Driver['status']) => {
  const types = {
    active: 'success',
    on_leave: 'warning',
    inactive: 'danger'
  }
  return types[status]
}

const getStatusText = (status: Driver['status']) => {
  const texts = {
    active: '在职',
    on_leave: '休假',
    inactive: '离职'
  }
  return texts[status]
}

const resetFilters = () => {
  searchQuery.value = ''
  statusFilter.value = ''
  licenseFilter.value = ''
  ElMessage.success('筛选条件已重置')
}

const viewDriver = (driver: Driver) => {
  selectedDriver.value = driver
  showDetailDialog.value = true
}

const editDriver = (driver: Driver) => {
  editingDriver.value = driver
  Object.assign(driverForm, driver)
  showAddDialog.value = true
}

const handleCommand = (command: { action: string; driver: Driver }) => {
  const { action, driver } = command
  
  switch (action) {
    case 'trips':
      ElMessage.info(`查看 ${driver.name} 的行程记录`)
      break
    case 'violations':
      ElMessage.info(`查看 ${driver.name} 的违章记录`)
      break
    case 'performance':
      ElMessage.info(`查看 ${driver.name} 的绩效评估`)
      break
    case 'delete':
      ElMessageBox.confirm(
        `确定要删除驾驶员 ${driver.name} 吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        const index = drivers.value.findIndex(d => d.id === driver.id)
        if (index > -1) {
          drivers.value.splice(index, 1)
          ElMessage.success('删除成功')
        }
      })
      break
  }
}

const saveDriver = () => {
  if (editingDriver.value) {
    // 编辑现有驾驶员
    const index = drivers.value.findIndex(d => d.id === editingDriver.value!.id)
    if (index > -1) {
      drivers.value[index] = { 
        ...editingDriver.value, 
        ...driverForm,
        totalTrips: editingDriver.value.totalTrips,
        totalMileage: editingDriver.value.totalMileage,
        rating: editingDriver.value.rating
      }
      ElMessage.success('驾驶员信息更新成功')
    }
  } else {
    // 添加新驾驶员
    const newDriver: Driver = {
      id: Date.now(),
      ...driverForm,
      currentVehicle: '',
      totalTrips: 0,
      totalMileage: 0,
      rating: 5.0
    }
    drivers.value.push(newDriver)
    ElMessage.success('驾驶员添加成功')
  }
  
  cancelEdit()
}

const cancelEdit = () => {
  showAddDialog.value = false
  editingDriver.value = null
  Object.assign(driverForm, {
    name: '',
    gender: 'male',
    age: 25,
    phone: '',
    idCard: '',
    licenseNumber: '',
    licenseType: '',
    experience: 0,
    status: 'active',
    hireDate: '',
    address: '',
    emergencyContact: '',
    emergencyPhone: '',
    notes: ''
  })
}

// 组件挂载时加载数据
onMounted(() => {
  // 这里可以调用API加载实际数据
})
</script>

<style scoped>
.el-card {
  border-radius: 8px;
}

.el-table {
  border-radius: 8px;
}
</style>